<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible"  modal-append-to-body="true" append-to-body="true">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      <el-form-item label="所属杆件" prop="gjbh">
        <el-select v-model="formData.gjbh" filterable placeholder="请选择所属杆件">
          <el-option
            v-for="dict in gjlist"
            :key="dict.gjbh"
            :label="dict.gjmc"
            :value="dict.gjbh"
             @click="onClickGJ(dict)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="sblx">
        <el-select v-model="formData.sblx" placeholder="请选择设备类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.DEVICE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            @click="onClickSBLX(dict)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称(自动生成)" prop="sbmc">
        <el-input v-model="formData.sbmc" placeholder="设备名称自动生成"  readonly/>
      </el-form-item>

      <el-form-item label="设备编号(自动生成)" prop="sbid">
        <el-input v-model="formData.sbid" placeholder="设备唯一编号默认自动生成" readonly/>
      </el-form-item>
      <el-form-item label="所属部门" prop="ssbm">
        <el-select v-model="formData.ssbm" placeholder="请选择设备所属部门">
          <el-option
            v-for="dict in bmlist"
            :key="dict.id"
            :label="dict.name"
            :value="dict.name" 
          />
        </el-select>
      </el-form-item>
      
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { deviceinfoApi, deviceinfoVO } from '@/api/deviceinfo/deviceinfo'
import { intersectionApi,   } from '@/api/intersection/intersection'
/** 设备 表单 */
defineOptions({ name: 'DeviceinfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  lkbh: undefined,
  sblx: undefined,
  sbid: undefined,
  sbmc: undefined,
  gjbh: undefined,
  gjmc:undefined,
  sblxmc:undefined,
  ssbm:undefined,
})
const formRules = reactive({
  gjbh:[{required:true, message:"请选择杆件"}],
  sblx:[{required:true, message:"请选择设备类型"} ],
  sbmc:[{required:true, message:"请输入设备名称"} ], 
})
const formRef = ref() // 表单 Ref
const props = defineProps<{
  gjbh?: String // 杆件编号（主表的关联字段）
}>()

//获取最新的相同类型的设备编号

const  getLastSBID = async( ) =>{ 
  const data = await intersectionApi.getdeviceinfopage({pageNo:1, pageSize:10,sblx:  formData.value.sblx, gjbh: formData.value.gjbh})
  let currentcount = data.list.length + 1
  if(currentcount>=10){
    formData.value.sbid = formData.value.sbid  + currentcount
  }else{
    formData.value.sbid = formData.value.sbid + "0" + currentcount
  }
  
}

const  onClickGJ = (dict) =>{
  formData.value.sbid = dict.gjbh  +((typeof  formData.value.sblx  =="undefined") ?'': formData.value.sblx )
  formData.value.gjmc = dict.gjmc
  formData.value.gjbh = dict.gjbh 
  formData.value.sbmc = dict.gjmc+"-" + ((typeof  formData.value.sblxmc  =="undefined") ?'': formData.value.sblxmc )

  getLastSBID()
}
const  onClickSBLX = (dict) =>{
  console.log("formData:",formData) 
  formData.value.sbid =  formData.value.gjbh + dict.value 
  formData.value.sblxmc = dict.label
  formData.value.sbmc =   ((typeof  formData.value.gjmc  =="undefined") ?'': formData.value.gjmc ) +"-" + dict.label

  getLastSBID()
}

/** 查询列表 */
const gjlist = ref<Record<string, any>[]>([]);
const getGJList = async () => { 
  try {
    if(props.gjbh){
      const data = await intersectionApi.getGJList({pageNo:1, pageSize:1000, gjbh: props.gjbh})
      gjlist.value =  data.list;
      //当只有一条记录时更新
      formData.value.gjmc = data.list[0].gjmc

      
    }else{
      const data = await intersectionApi.getGJList({pageNo:1, pageSize:1000})
      gjlist.value =  data.list;
    }
    
  } finally {
     
  }
}


const bmlist = ref<Record<string, any>[]>([]);
const getbmlist = async () => { 
  try {
    const data = await intersectionApi.deptsimple({})
      bmlist.value =  data;
    
  } finally {
     
  }
}
getbmlist()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      let res = await deviceinfoApi.getdeviceinfo(id)
      formData.value = res
      //formData.value.gjmc = res.sbmc
      getGJList()
    } finally {
      formLoading.value = false
    }
  }else{
    getGJList()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as deviceinfoVO
    if (formType.value === 'create') {
      await deviceinfoApi.createdeviceinfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await deviceinfoApi.updatedeviceinfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    lkbh: undefined,
    sblx: undefined,
    sbid: undefined,
    sbmc: undefined,
    gjbh: undefined,
    gjmc:undefined,
  }
  formRef.value?.resetFields()
}
</script>